package com.device.util;

import java.net.URLDecoder;
import java.net.URLEncoder;
import javax.servlet.http.Cookie;
import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

/**
 * @author:刘高博
 * @date:2017年4月19日
 * @说明:cookie工具类
 **/
@Slf4j
public class CookieUtil {
	/**
	 *@param response
	 *@param name
	 *@param value
	 *@param maxAge -1 表示浏览器关闭cookie就消失
	 *@return 添加cookie
	 **/
	public static void addCookie(HttpServletResponse response, String name,
			String value, int maxAge) {
		try {
			Cookie cookie = new Cookie(name, URLEncoder.encode(value, "utf-8"));
			cookie.setMaxAge(maxAge);
			cookie.setPath("/");
			response.addCookie(cookie);
		} catch (UnsupportedEncodingException e) {
			log.error(e.getMessage());
		}
	}

	/**
	 *@return 得到cookie
	 **/
	public static String getValue(HttpServletRequest request, String name) {
		String value = null;
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (name.equals(cookie.getName())) {
					try {
						value = URLDecoder.decode(cookie.getValue(), "utf-8");
					} catch (UnsupportedEncodingException e) {
						log.error(e.getMessage());
					}
					break;
				}
			}
		}
		return value;
	}

	/** 
	 *@return 删除
	 **/
	public static void delCookie(HttpServletResponse response, String name) {
		Cookie cookie = new Cookie(name, null);
		cookie.setMaxAge(0);
		cookie.setPath("/");
		response.addCookie(cookie);
	}
}
